/*
 * @Date: 2024-11-22 17:27:41
 * @Author: LiSong
 * @LastEditors: g05047
 * @LastEditTime: 2024-12-24 08:59:09
 * @Description: 
 */
import { defineComponent, h, watch, reactive, ref, onBeforeUnmount, onBeforeMount } from "vue";
import "element-plus/es/components/select/style/css";
import { ElAutocomplete } from "element-plus";
import { storeToRefs } from 'pinia';
import { useTagsViewRoutes } from '@/stores/tagsViewRoutes';

const { tagsViewRoutes } = storeToRefs(useTagsViewRoutes());

export default defineComponent({
  emits: ["update:modelValue"],
  props: {
    modelValue: {
      type: String,
      default: ''
    },
  },

  setup(props, { emit, attrs }) {
    const inputValue = ref(props.modelValue);
    const toolsState = reactive({
      selOptions: []
    })
    function loadToolOptions() {
      if (toolsState.selOptions.length > 0) {
        return;
      } else {
        for (let v of tagsViewRoutes.value) {
          if (v.meta?.isHide) continue;
          if (v.children && v.children.length > 0) continue;
          toolsState.selOptions.push({
            link: v.path, value: v.meta.title
          });
        }
      }
    }
    function createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    }
    function clearToolOptions() {
      toolsState.selOptions = []
    }
    // 处理选中变化
    const onSelect = (item) => {
      inputValue.value = item.link;
      emit('update:modelValue', item.link);
    };
    // 处理输入变化
    const onInputChange = (value) => {
      inputValue.value = value;
      emit('update:modelValue', value);
    };
    // 处理文本输入
    function handleFetchSuggestions(queryString, cb) {
      const results = queryString
        ? toolsState.selOptions.filter(createFilter(queryString))
        : toolsState.selOptions
      cb(results)
    }
    onBeforeMount(() => {
      loadToolOptions()
    })
    onBeforeUnmount(() => {
      clearToolOptions()
    })
    return () => {
      const props = {
        ...attrs,
        key: String(attrs.multiple),
        modelValue: inputValue.value,
        'onUpdate:modelValue': onInputChange,
        fetchSuggestions: handleFetchSuggestions, // 确保过滤函数是正确的
        onSelect: onSelect,
        placeholder: '请输入内容...',
      }
      return h(ElAutocomplete, props)
    }
  }
})
